from django.shortcuts import render
from django.http import HttpResponse
from .models import Mirna, Disease,Premir
import pandas as pd
import json
import gseapy as gp
from mysite import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import os


# Create your views here.
def index(request):
    test = "test!!!!!!"
    return render(request,"mircards/index.html", {"a": test})


@csrf_exempt
def search(request):
    if request.method == "POST":
        result = []
        tmp = {}
        mir = request.POST.get('mir')
        flag = request.POST.get('flag')
        # print("The name is:"+mir)
        if(flag=="mir"):
            query_res = Mirna.objects.filter(mature_id=mir)
            res_num = query_res.count()
            # print(res_num)
            for i in query_res:
                tmp['ma1_id'] = i.mature_id
                tmp['ma1_acc'] = i.accession
                tmp['ma1_seq'] = i.sequence
                tmp['ma1_des'] = i.description
                tmp['ma1_chr'] = i.mature_chrom.split(";")[1]
                tmp['pre_mir'] = i.pre_mir
                tmp['num'] = res_num
            if res_num:
                join_mir = tmp['pre_mir'].split(";")[0]
                query_res2 = Premir.objects.filter(id=join_mir)
                for i in query_res2:
                    # tmp['pre_acc'] = i.accession
                    tmp['pre_seq'] = i.sequence
                    tmp['pre_chrom'] = i.pre_chrom
                    tmp['pre_ma1'] = i.pre_mature1
                    tmp['pre_ma2'] = i.pre_mature2
                    tmp['pre_fam'] = i.pre_family
                if tmp['ma1_id']==tmp['pre_ma1']:
                    second_mir = tmp['pre_ma2']
                else:
                    second_mir = tmp['pre_ma1']
                query_res3 = Mirna.objects.filter(mature_id=second_mir)
                for i in query_res3:
                    tmp['ma2_id'] = i.mature_id
                    tmp['ma2_acc'] = i.accession
                    tmp['ma2_seq'] = i.sequence
                    tmp['ma2_des'] = i.description
                    tmp['ma2_chr'] = i.mature_chrom.split(";")[1]
            result.append(tmp)
            return JsonResponse(result, safe=False)
        else:
            query_res = Premir.objects.filter(id=mir)
            res_num = query_res.count()
            for i in query_res:
                tmp['pre_mir'] = i.id
                tmp['pre_seq'] = i.sequence
                tmp['pre_ma1'] = i.pre_mature1
                tmp['pre_ma2'] = i.pre_mature2
                tmp['pre_fam'] = i.pre_family
                tmp['pre_chrom'] = i.pre_chrom
                tmp['num'] = res_num
            if res_num:
                query_res2 = Mirna.objects.filter(mature_id=tmp['pre_ma1'])
                for i in query_res2:
                    tmp['ma1_id'] = i.mature_id
                    tmp['ma1_acc'] = i.accession
                    tmp['ma1_seq'] = i.sequence
                    tmp['ma1_des'] = i.description
                    tmp['ma1_chr'] = i.mature_chrom.split(";")[1]
                query_res3 = Mirna.objects.filter(mature_id=tmp['pre_ma2'])
                for i in query_res3:
                    tmp['ma2_id'] = i.mature_id
                    tmp['ma2_acc'] = i.accession
                    tmp['ma2_seq'] = i.sequence
                    tmp['ma2_des'] = i.description
                    tmp['ma2_chr'] = i.mature_chrom.split(";")[1]
            result.append(tmp)
            return JsonResponse(result, safe=False)


@csrf_exempt
def browse(request):
    if request.method == "POST":
        print("hello\n")
        result = []
        tmp = {}
        query_res = Premir.objects.all()
        for i in query_res:
            tmp['pre_mir'] = i.id
            tmp['pre_seq'] = i.sequence
            tmp['pre_ma1'] = i.pre_mature1
            tmp['pre_ma2'] = i.pre_mature2
            tmp['pre_fam'] = i.pre_family
            tmp['pre_chrom'] = i.pre_chrom
            result.append(tmp)
    return JsonResponse(result,safe=False)


def download_results(request):
    select_value = request.GET.get('select_value')
    result = request.GET.get('result')

    if select_value == 'mir':
        # 如果选择值为 'mir'，则处理卡片类型的结果
        if result:
            # 从字符串中提取 Mircards 对象
            mircard_id = result.split(" ")[-1][1:-1]  # 提取出 Mircards 对象的 ID，如 '(hsa-miR-410-5p)'，并去掉括号
            # 根据 ID 获取 Mircards 对象
            try:
                query_res = Mirna.objects.get(Mature_id=mircard_id)
                # 将 Mircards 对象转换为字典
                result_dict = {
                    'Mature ID': query_res.Mature_id,
                    'Accession': query_res.Accession,
                    'Description': query_res.Description,
                    'Sequence': query_res.Sequence,
                    'Seed Sequence': query_res.Seed_seq,
                    'Mature Chromosome': query_res.mature_chrom,
                    'Pre-miRNA': query_res.pre_mir,
                    'Evidence': query_res.evidence,
                }
                # 将字典转换为 DataFrame
                df = pd.DataFrame(result_dict, index=[0])

            except Mirna.DoesNotExist:
                return HttpResponse("No miRNA matching query")

    else:
        # 如果选择值不为 'mir'，则处理表格类型的结果
        if result:
            # 将结果字符串转换为列表
            result_list = json.loads(result)
            # 将列表转换为 DataFrame
            df = pd.DataFrame(result_list)

    if df.empty:
        # 如果 DataFrame 为空，则返回没有结果可下载的消息
        return HttpResponse("No results to download")
    else:
        # 如果 DataFrame 不为空，则将其写入 Excel 文件并提供下载
        output_path = 'search_results.xlsx'
        df.to_excel(output_path, index=False)

        with open(output_path, 'rb') as f:
            response = HttpResponse(f.read(), content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename="search_results.xlsx"'
            return response


def mirna_enrich(request):

    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        # 将上传的文件保存到服务器上的临时位置
        with open(os.path.join(settings.MEDIA_ROOT, 'uploads', myfile.name), 'wb+') as destination:
            for chunk in myfile.chunks():
                destination.write(chunk)

        # 获取上传文件的路径
        file_path = os.path.join(settings.MEDIA_ROOT, 'uploads', myfile.name)
        rnk = pd.read_csv(file_path, header=None, sep="\t")
        # 运行 prerank 方法生成结果图片
        pre_res = gp.prerank(rnk=rnk, gene_sets='mircards/static/examples/mirna_set.gmt', threads=4, min_size=5,
                              max_size=1000,
                              permutation_num=1000,
                              outdir='mircards/static/enrichment/prerank_result',
                              format='png', seed=6)

        terms = pre_res.res2d.Term
        axs = pre_res.plot(terms=terms[1], show_ranking=True)

        # 获取结果的前几行数据
        result_table = pre_res.res2d.head()  # 获取前几行结果数据

        # 将结果传递给模板
        return render(request, 'mircards/enrich_results.html', {'result': axs, 'result_table': result_table})
        # 获取生成的结果图片文件名
        #result_image = pre_res.prerank        #axs = pre_res.plot(terms=terms[1], show_ranking=True)
        # 保存结果图片到静态文件夹
        #image_path = os.path.join('enrichment', 'prerank_result',result_image)
        #image_url = os.path.join(settings.STATIC_URL, image_path)
        # 将结果图片路径传递给模板
        #return render(request, 'mircards/enrich_results.html', {'result_image': image_url})
    return render(request, 'mircards/index.html')